﻿using System;
using System.Text.RegularExpressions;

namespace N2.Web
{
	public static class CssMinifier
	{
		//Taken from [https://BlogEngine.svn.codeplex.com/svn/BlogEngine/DotNetSlave.BusinessLogic/Web/HttpHandlers/CssHandler.cs]
		public static string StripWhitespace(string body)
		{
			body = body.Replace("  ", " ");
			body = body.Replace(Environment.NewLine + Environment.NewLine + Environment.NewLine, String.Empty);
			body = body.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);
			body = body.Replace(Environment.NewLine, String.Empty);
			body = body.Replace("\t", string.Empty);
			body = body.Replace(" {", "{");
			body = body.Replace(" :", ":");
			body = body.Replace(": ", ":");
			body = body.Replace(", ", ",");
			body = body.Replace("; ", ";");
			body = body.Replace(";}", "}");
//			body = body.Replace("}.", "} .");

			// sometimes found when retrieving CSS remotely
			body = body.Replace(@"?", string.Empty);

			//body = Regex.Replace(body, @"/\*[^\*]*\*+([^/\*]*\*+)*/", "$1");
			body = Regex.Replace(body, @"(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,}(?=&nbsp;)|(?<=&ndsp;)\s{2,}(?=[<])", String.Empty);

			//Remove comments from CSS
			body = Regex.Replace(body, @"/\*[\d\D]*?\*/", string.Empty);
			body = Regex.Replace(body, @"//.*$", "\n");
			
			return body;
		}

	}
}
